package com.msb.mall.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.msb.mall.common.constant.ProductConstant;
import com.msb.mall.common.dto.MemberPrice;
import com.msb.mall.common.dto.SkuHasStockDto;
import com.msb.mall.common.dto.SkuReductionDTO;
import com.msb.mall.common.dto.SupBoundsDTO;
import com.msb.mall.common.dto.es.SkuESModel;
import com.msb.mall.common.utils.R;
import com.msb.mall.product.entity.*;
import com.msb.mall.product.feign.CouponFeignService;
import com.msb.mall.product.feign.SearchFeignService;
import com.msb.mall.product.feign.WareSkuFeignService;
import com.msb.mall.product.service.*;
import com.msb.mall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.mall.common.utils.PageUtils;
import com.msb.mall.common.utils.Query;

import com.msb.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private WareSkuFeignService wareSkuFeignService;
    @Autowired
    private SearchFeignService searchFeignService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfoVO(SpuInfoVO spuInfoVO) {
        // 1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setPublishStatus(0); // 默认为新建
        this.save(spuInfoEntity);
        // 2.保存spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        List<String> decripts = spuInfoVO.getDecript();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decripts));
        spuInfoDescService.save(spuInfoDescEntity);
        // 3.保存spu的图片集 pms_spu_images
        List<String> images = spuInfoVO.getImages();
        List<SpuImagesEntity> spuImagesEntities = images.stream().map(img -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(img);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(spuImagesEntities);
        // 4.保存spu的规格参数信息 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVO.getBaseAttrs();
        // 对规格数据做对应的处理
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        // 5 保存SPU对应的所有的sku信息
        List<Skus> skus = spuInfoVO.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(item -> {
                // skuInfoService
                // 5.1 保存sku的基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoVO.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoVO.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                String skuDefaultImg = "";
                List<Images> images1 = item.getImages();
                for (Images images2 : images1) {
                    if (images2.getDefaultImg() == 1) {
                        // 表示默认的图片
                        skuDefaultImg = images2.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(skuDefaultImg);
                skuInfoService.save(skuInfoEntity);
                // 5.2 保存sku的图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = images1.stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    return skuImagesEntity;
                }).filter(img -> img.getDefaultImg() == 1).collect(Collectors.toList()); // 为控的图片不需要保存
                skuImagesService.saveBatch(skuImagesEntities);

                // 5.3 保存满减信息，满折信息，会员价格信息，sku的优惠信息 pms_sku_ladder sms_sku_full_reduction sms_sku_ladder_price
                SkuReductionDTO skuReductionDTO = new SkuReductionDTO();
                BeanUtils.copyProperties(item, skuReductionDTO);
                skuReductionDTO.setSkuId(skuInfoEntity.getSkuId());
                // 设置会员价
                if (item.getMemberPrice() != null && item.getMemberPrice().size() > 0) {
                    List<MemberPrice> list = item.getMemberPrice().stream().map(memberPrice -> {
                        MemberPrice mDto = new MemberPrice();
                        BeanUtils.copyProperties(memberPrice, mDto);
                        return mDto;
                    }).collect(Collectors.toList());
                    skuReductionDTO.setMemberPrice(list);
                }

                R r = couponFeignService.saveFullReductionInfo(skuReductionDTO);
                if (r.getCode() != 0) {
                    log.error("调用Coupon服务存储满减信息，满折信息，会员价格信息操作失败");
                }

                // 5.4 sku的销售属性组合 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(sale -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(sale, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

            });
        }
        // 6.保存spu的积分信息 sms_spu_bounds
        Bounds bounds = spuInfoVO.getBounds();
        SupBoundsDTO supBoundsDTO = new SupBoundsDTO();
        BeanUtils.copyProperties(bounds, supBoundsDTO);
        supBoundsDTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(supBoundsDTO);
        if (r.getCode() != 0) {
            log.error("调用Coupon服务存储积分信息操作失败");
        }

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wapper.and(w -> {
                w.eq("id", key)
                        .or().like("spu_name", key)
                        .or().like("spu_description", key);
            });
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            wapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equals(brandId)) {
            wapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equals(catelogId)) {
            wapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wapper
        );
        IPage<SpuInfoVO> page1 = new Page<SpuInfoVO>();
        List<SpuInfoVO> voList = page.getRecords().stream().map(item -> {
            SpuInfoVO spuInfoVO = new SpuInfoVO();
            CategoryEntity categoryEntity = categoryService.getById(item.getCatalogId());
            spuInfoVO.setCatalogName(categoryEntity.getName());
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            spuInfoVO.setBrandName(brandEntity.getName());
            BeanUtils.copyProperties(item, spuInfoVO);
            return spuInfoVO;
        }).collect(Collectors.toList());
        page1.setRecords(voList);
        page1.setTotal(page.getTotal());
        page1.setSize(page.getSize());
        page1.setCurrent(page.getCurrent());

        return new PageUtils(page1);
    }

    /**
     * 实现商品上架-》商品相关数据存储到Elasticsearch中
     * 1.根据SpuId查询出相关信息
     *  封装到对应的对象中
     *  2.将对象存储到Elasticsearch中 =》 调用mall-search远程模块的接口
     *  3.更新spu的状态为上架
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {

        // 1.根据SpuId查询出相关信息，封装到对应的对象中
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        List<SkuESModel.Attrs> skuESModelAttrs = getAttrModels(spuId);
        List<Long> skuIds = skuInfoEntities.stream().map(sku -> sku.getSkuId()).collect(Collectors.toList());
        Map<Long, Boolean> hasStockMap = getHasStockMap(skuIds);
        List<SkuESModel> skuEsModels = skuInfoEntities.stream().map(sku -> {
            SkuESModel skuEsModel = new SkuESModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSubTitle(sku.getSkuTitle());
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            // 是否有库存  --》 库存系统查询 一次调用获取所有的skuId对应的库存信息
            if (hasStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(hasStockMap.get(sku.getSkuId()));
            }
            // 热度评分 --》 默认给0即可
            skuEsModel.setHotScore(0L);
            // 品牌和类型的名称
            BrandEntity brand = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(category.getName());
            // 对应规格参数
            skuEsModel.setAttrs(skuESModelAttrs);
            return skuEsModel;
        }).collect(Collectors.toList());


        // 2.远程调用mall-search远程模块的接口，将对象存储到Elasticsearch中
        R r = searchFeignService.productStatusUp(skuEsModels);
        // 根据对应的状态更新商品状态
        if (r.getCode() == 0) {
            // 远程调用成功 更新商品的状态为 上架
            baseMapper.updateSpuStatusUp(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else{

        }

        // 3.更新spu的状态为上架




    }

    /**
     * 获取skuId对应的是否有库存状态
     * @param skuIds
     * @return
     */
    private Map<Long, Boolean> getHasStockMap(List<Long> skuIds) {

        if (!CollectionUtils.isEmpty(skuIds)) {
            return null;
        }
        try {
            List<SkuHasStockDto> skusHasStock = wareSkuFeignService.getSkusHasStock(skuIds);
            return skusHasStock.stream().collect(Collectors.toMap(SkuHasStockDto::getSkuId, SkuHasStockDto::getHasStock));
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取spuId对应的所有规格参数
     * @param spuId
     * @return
     */
    private List<SkuESModel.Attrs> getAttrModels(Long spuId) {
        // 对应的规格参数 根据spuId查询出所有相关规格参数
        // (1) product_attr_value
        // (2) attr 里面的search_type是否需要检索[0-不需要，1-需要]
        List<ProductAttrValueEntity> productAttrValues = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = productAttrValues.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        // 查询出所有需要检索的规格参数编号
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        List<SkuESModel.Attrs> skuESModelAttrs = productAttrValues.stream().filter(item -> searchAttrIds.contains(item.getAttrId()))
                .map(item -> {
                    SkuESModel.Attrs attrs = new SkuESModel.Attrs();
                    /*attrs.setAttrId(item.getAttrId());
                    attrs.setAttrName(item.getAttrName());
                    attrs.setAttrValue(item.getAttrValue());*/
                    BeanUtils.copyProperties(item, attrs);
                    return attrs;
                }).collect(Collectors.toList());
        return skuESModelAttrs;
    }

}